<?php
/*
 * @@Copyright (C), 2021-2022: 恒盛时代
 * @Author: zhouzhou
 * @Date: 2021/11/23
 * @Description: 群组用户表
 */

namespace App\Models;

use App\Http\Controllers\WebApi\Business\ConfigBusiness;
use App\Jobs\GroupUserTask;
use App\Services\Aliyun\upload\AliyunUploadServices;
use App\Services\Configs\DefaultService;
use App\Services\Huanxin\ChatServices;
use App\Services\Netease\ChatServices as NeteaseChatServices;
use App\Services\RongCloud\ChatService as RongChatService;
use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Services\Huanxin\GroupServices;
use App\Services\RongCloud\GroupService;
use App\Services\Netease\GroupServices as NetGroupServices;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;
use OSS\Core\OssException;
use OSS\OssClient;


class ImGroupUser extends BaseModel
{
    use SoftDeletes;
    protected $table = 'im_group_user';

    /**
     * 关联群组表
     */
    public function group()
    {
        return $this->belongsTo(ImGroup::class, 'im_gid', 'im_gid');
    }

    /**
     * 关联角色表
     */
    public function role()
    {
        return $this->belongsTo(ImRole::class, 'role', 'id');
    }

    /**
     * 关联用户表
     */
    public function user()
    {
        return $this->belongsTo(ImUsers::class, 'user_id', 'id');
    }

    /**
     * 邀请人关联用户表
     */
    public function invite()
    {
        return $this->belongsTo(ImUsers::class, 'other_uid', 'id')
            ->select(['id', 'nickname', 'headimg']);
    }

    /**
     * 删除人关联用户表
     */
    public function remove()
    {
        return $this->belongsTo(ImUsers::class, 'remove_uid', 'id')
            ->select(['id', 'nickname', 'headimg']);
    }

    /**
     * @desc 新增多个群组组员
     * @param string $member 逗号隔开
     * @param string $imGid 群组id
     * @param string $userId 邀请人
     * @author zhouzhou
     * @time 2021/11/23 15:23
     */
    public function addMoreMemebr($member, $imGid, $userId = 0, $auditStatus = 1, $applyNote = '')
    {
        $memberList = explode(",",$member );
        $groupUser = [];
        foreach ($memberList as $key =>$val)
        {
            $groupUser[$key]['im_gid'] = $imGid;
            $groupUser[$key]['user_id'] = $val;
            $groupUser[$key]['other_uid'] = $userId;
            $groupUser[$key]['audit_status'] = $auditStatus;
            $groupUser[$key]['apply_note'] = $applyNote;
            $groupUser[$key]['created_at'] = time();
            $groupUser[$key]['updated_at'] = time();
        }

        return $this->insert($groupUser);
    }


    /**
     * @desc 所有群员管理
     * @param string $imGid 群组环信id
     * @param int $userId 用户id
     * @param int $limit 每页默认10个
     * @param int $offset 从那条数据开始
     * @return mixed
     * @author zhouzhou
     * @time 2021/11/23 16:50
     */
    public function memberList($imGid, $userId = 0, $limit = 10, $offset = 0)
    {
        $list = $this->select('id', 'im_gid', 'user_id', 'role', 'status')->with(['group' => function($q){
            $q->select('im_gid','name','description','face');
        }])->with(['role' => function($q){
            $q->select('id','name');
        }])->with(['user' => function($q){
            $q->select('id','nickname','headimg');
        }])->where(['im_gid'=>$imGid, 'audit_status'=>1])->whereIn('status', [0,3])
            ->orderBy('id', 'desc')
            ->limit($limit)
            ->offset($offset)
            ->get();

        return $list;
    }

    /**
     * @desc 群主群管新增群组成员
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/23 14:58
     */
    public function addSingleMember($input, $userId = 0)
    {
        $ImGroup = new ImGroup();
        $userIdCount = $ImGroup->where('im_gid',$input['im_gid'])->count();

        $imGroup = $ImGroup->where('im_gid', $input['im_gid'])->first();
        if (!$imGroup)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        $imGroupUser = $this->where(['im_gid' => $input['im_gid'], 'user_id' => $input['member_id']])->whereIn('status', [0,3])->first();
        if ($imGroupUser)
        {
            return ['code' => 1, 'msg' => '用户已经是群成员'];
        }

        // 自己在群的权限
        $imGroupUserRole = $this->where(['im_gid' => $input['im_gid'], 'user_id' => $userId])->whereIn('status', [0,3])->first();
        if (!$imGroupUserRole)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        $option = ConfigBusiness::thirdPartyFirst('im');
        $optionValue = $option->value;

        // 等于1 直接审核到群成员里面,或者群主或者管理员邀请，直接过审核
        if ($imGroup['is_allow'] == 1 || in_array($imGroupUserRole['role'], [1,2]))
        {
            switch($optionValue)
            {
                case ($optionValue == DefaultService::HUANXIN_IM):  // 环信
                    $groupServices= new GroupServices();
                    $groupServiceInfo = $groupServices->addChatGroupsMember($input['im_gid'],$input['member_id']);
                    if ($groupServiceInfo['code'] != 200)
                    {
                        return ['code' => 1, 'msg' => '添加失败'];
                    }

                    GroupUserTask::dispatch(['group_id'=>$input['im_gid'],'member_id'=>$input['member_id'],'group_name'=>$imGroup['name'],'user_id'=>$userId,'type'=>1]);
                    break;
                case ($optionValue == DefaultService::RONGYUN_IM):  // 融云
                    $groupServices= new GroupService();
                    $groupServiceInfo = $groupServices->joinGroup($input['member_id'], $input['im_gid'], $imGroup['name']);
                    if ($groupServiceInfo['code'] != 200)
                    {
                        return ['code' => 1, 'msg' => '添加失败'];
                    }

                    GroupUserTask::dispatch(['group_id'=>$input['im_gid'],'member_id'=>$input['member_id'],'group_name'=>$imGroup['name'],'user_id'=>$userId,'type'=>2]);
                    break;
                case ($optionValue == DefaultService::NETEASE_IM):  // 网易
                    $groupServices= new NetGroupServices();
                    $groupServiceInfo = $groupServices->addIntoGroup($input['im_gid'],$userId, [$input['member_id']]);
                    if ($groupServiceInfo['code'] != 200)
                    {
                        return ['code' => 1, 'msg' => '添加失败'];
                    }

                    GroupUserTask::dispatch(['group_id'=>$input['im_gid'],'member_id'=>$input['member_id'],'group_name'=>$imGroup['name'],'user_id'=>$userId,'type'=>3]);
                    break;
                default:
                    $groupServiceInfo['code'] = 400;
                    break;
            }


        }

        $this->im_gid = $input['im_gid'];
        $this->user_id = $input['member_id'];
        $this->apply_note = $input['apply_note'] ?? '';
        $this->other_uid = $userId;
        $this->audit_status = ($imGroup['is_allow'] == 1 || in_array($imGroupUserRole['role'], [1,2])) ? 1 : 0;
        $flag = $this->save();
        if (!$flag)
        {
            return ['code' => 1, 'msg' => '添加失败'];
        }

        if ($imGroup['is_allow'] == 1 || in_array($imGroupUserRole['role'], [1,2]))
        {
            $imGroup->increment('users_count');
        }

        // 群人数小于4 更新群组头像
        if ($userIdCount < 4)
        {
            $fileUrl = $this->updateGroupHeading($input['im_gid']);
            if ($fileUrl)
            {
                $imGroup->face = $fileUrl;
            }
        }

        return ['code' => 0, 'msg' => '添加成功','data'=>['group_id' => $imGroup->im_gid, 'face'=>$imGroup->face]];
    }

    /**
     * @desc 批量新增群组成员
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/23 14:58
     */
    public function addManyMember($input, $userId = 0)
    {
        $ImGroup = new ImGroup();
        $userIdCount = $ImGroup->where('im_gid',$input['im_gid'])->count();

        $imGroup = $ImGroup->where('im_gid', $input['im_gid'])->first();
        if (!$imGroup)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        // 自己在群的权限
        $imGroupUserRole = $this->where(['im_gid' => $input['im_gid'], 'user_id' => $userId])->whereIn('status', [0,3])->first();
        if (!$imGroupUserRole)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        $option = ConfigBusiness::thirdPartyFirst('im');
        $optionValue = $option->value;
        $member = $input['member_id'];
        $memberList = explode(",",$member);
        $service['usernames'] = $memberList;
        if ($imGroup['is_allow'] == 1 || in_array($imGroupUserRole['role'], [1,2]))
        {
            switch($optionValue)
            {
                case ($optionValue == DefaultService::HUANXIN_IM):  // 环信
                    $groupServices= new GroupServices();
                    $groupServiceInfo = $groupServices->addChatGroupsMembers($input['im_gid'], $service);
                    if ($groupServiceInfo['code'] != 200)
                    {
                        return ['code' => 1, 'msg' => '添加失败'];
                    }

                    GroupUserTask::dispatch(['group_id'=>$input['im_gid'],'member_id'=>$input['member_id'],'group_name'=>$imGroup['name'],'user_id'=>$userId,'type'=>1]);
                    break;
                case ($optionValue == DefaultService::RONGYUN_IM):  // 融云
                    $groupServices= new GroupService();
                    $groupServiceInfo = $groupServices->joinGroup($memberList, $input['im_gid'], $imGroup['name']);
                    if ($groupServiceInfo['code'] != 200)
                    {
                        return ['code' => 1, 'msg' => '添加失败'];
                    }
                    GroupUserTask::dispatch(['group_id'=>$input['im_gid'],'member_id'=>$input['member_id'],'group_name'=>$imGroup['name'],'user_id'=>$userId,'type'=>2]);
                    break;
                case ($optionValue == DefaultService::NETEASE_IM):  // 网易
                    $groupServices= new NetGroupServices();
                    $groupServiceInfo = $groupServices->addIntoGroup($input['im_gid'],$userId, $memberList);
                    if ($groupServiceInfo['code'] != 200)
                    {
                        return ['code' => 1, 'msg' => '添加失败'];
                    }
                    GroupUserTask::dispatch(['group_id'=>$input['im_gid'],'member_id'=>$input['member_id'],'group_name'=>$imGroup['name'],'user_id'=>$userId,'type'=>3]);
                    break;
                default:
                    $groupServiceInfo['code'] = 400;
                    break;
            }



        }

        $auditStatus = ($imGroup['is_allow'] == 1 || in_array($imGroupUserRole['role'], [1,2])) ? 1 : 0;
        $applyNote = $input['apply_note'] ?? '';
        $this->addMoreMemebr($member, $input['im_gid'], $userId, $auditStatus, $applyNote);
        if ($auditStatus == 1)
        {
            $imGroup->increment('users_count', count($memberList));
        }

        // 群人数小于4 更新群组头像
        if ($userIdCount < 4)
        {
            $fileUrl = $this->updateGroupHeading($input['im_gid']);
            if ($fileUrl)
            {
                $imGroup->face = $fileUrl;
            }
        }

        return ['code' => 0, 'msg' => '添加成功','data'=>['group_id' => $imGroup->im_gid, 'face'=>$imGroup->face]];
    }

    /**
     * @desc 移除单个的群组成员
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/23 14:58
     */
    public function delSingleMember($input, $userId = 0)
    {
        $ImGroup = new ImGroup();
        $imGroup = $ImGroup->where('im_gid', $input['im_gid'])->first();
        if (!$imGroup)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        $imGroupUserRole = $this->where(['im_gid' => $input['im_gid'], 'user_id' => $userId])->whereIn('status', [0,3])->first();
        if ($imGroupUserRole && !in_array($imGroupUserRole['role'], [1,2]))
        {
            return ['code' => 1, 'msg' => '权限不足'];
        }

        $imGroupUser = $this->where(['im_gid' => $input['im_gid'], 'user_id' => $input['member_id']])->whereIn('status', [0,3])->first();
        if (!$imGroupUser)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        $option = ConfigBusiness::thirdPartyFirst('im');
        $optionValue = $option->value;
        switch($optionValue)
        {
            case ($optionValue == DefaultService::HUANXIN_IM):  // 环信
                $groupServices= new GroupServices();
                $groupServiceInfo = $groupServices->delChatGroupsMember($input['im_gid'],$input['member_id']);
                break;
            case ($optionValue == DefaultService::RONGYUN_IM):  // 融云
                $groupServices= new GroupService();
                $groupServiceInfo = $groupServices->quitGroup($input['member_id'], $input['im_gid']);
                break;
            case ($optionValue == DefaultService::NETEASE_IM):  // 网易
                $groupServices= new NetGroupServices();
                $groupServiceInfo = $groupServices->kickFromGroup($input['im_gid'],$userId, $input['member_id']);
                break;
            default:
                $groupServiceInfo['code'] = 400;
                break;
        }

        if ($groupServiceInfo['code'] != 200)
        {
            return ['code' => 1, 'msg' => '删除失败'];
        }

        $imGroupUser->remove_uid = $userId;
        $imGroupUser->updated_at = time();
        $imGroupUser->save();

        $imGroupUser->delete();
        if ($imGroupUser->trashed())
        {
            $imGroup->decrement('users_count');
            return ['code' => 0, 'msg' => '删除成功'];
        }
        else
        {
            return ['code' => 1, 'msg' => '删除失败'];
        }
    }

    /**
     * @desc 批量移除群组成员
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/23 14:58
     */
    public function delManyMember($input, $userId = 0)
    {
        $ImGroup = new ImGroup();
        $imGroup = $ImGroup->where('im_gid', $input['im_gid'])->first();
        if (!$imGroup)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        $imGroupUserRole = $this->where(['im_gid' => $input['im_gid'], 'user_id' => $userId])->whereIn('status', [0,3])->first();
        if ($imGroupUserRole && !in_array($imGroupUserRole['role'], [1,2]))
        {
            return ['code' => 1, 'msg' => '权限不足'];
        }

        $member = $input['member_id'];
        $memberList = explode(",",$member);

        $option = ConfigBusiness::thirdPartyFirst('im');
        $optionValue = $option->value;
        switch($optionValue)
        {
            case ($optionValue == DefaultService::HUANXIN_IM):  // 环信
                $groupServices= new GroupServices();
                $groupServiceInfo = $groupServices->delChatGroupsMembers($input['im_gid'], $input['member_id']);
                break;
            case ($optionValue == DefaultService::RONGYUN_IM):  // 融云
                $groupServices= new GroupService();
                $groupServiceInfo = $groupServices->quitGroup($memberList, $input['im_gid']);
                break;
            case ($optionValue == DefaultService::NETEASE_IM):  // 网易
                $groupServices= new NetGroupServices();
                $groupServiceInfo = $groupServices->kickFromGroups($input['im_gid'],$userId,json_encode($memberList));
                break;
            default:
                $groupServiceInfo['code'] = 400;
                break;
        }

        if ($groupServiceInfo['code'] != 200)
        {
            return ['code' => 1, 'msg' => '移除失败'];
        }

        $imGroupUsers = $this->where(['im_gid' => $input['im_gid']])->whereIn('user_id', $memberList)->get();
        if (!$imGroupUsers)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        $this->where(['im_gid' => $input['im_gid']])->whereIn('user_id', $memberList)->delete();
        $imGroup->decrement('users_count', count($memberList));

        return ['code' => 0, 'id' => $this->id, 'msg' => '删除成功'];
    }

    /**
     * @desc 群组管理员列表
     * @param string $imGid 群组环信id
     * @param int $userId 用户id
     * @param int $limit 每页默认10个
     * @param int $offset 从那条数据开始
     * @return mixed
     * @author zhouzhou
     * @time 2021/11/23 16:50
     */
    public function managerList($imGid, $userId = 0, $limit = 10, $offset = 0)
    {
        $list = $this->select('id', 'im_gid', 'user_id', 'role', 'status')->with(['group' => function($q){
            $q->select('im_gid','name','description','face');
        }])->with(['role' => function($q){
            $q->select('id','name');
        }])->with(['user' => function($q){
            $q->select('id','nickname','headimg');
        }])->where(['im_gid'=>$imGid, 'role'=>2])->whereIn('status', [0,3])
            ->orderBy('id', 'desc')
            ->limit($limit)
            ->offset($offset)
            ->get();

        return $list;
    }

    /**
     * @desc 升级群管理员
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/23 14:58
     */
    public function upManager($input, $userId = 0)
    {
        $ImGroup = new ImGroup();
        $imGroup = $ImGroup->where('im_gid', $input['im_gid'])->first();
        if (!$imGroup)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        if ($imGroup['user_id'] != $userId)
        {
            return ['code' => 1, 'msg' => '权限不足'];
        }

        $member = $input['member_id'];
        $memberList = explode(",",$member);

        foreach ($memberList as $key =>&$val)
        {
            $member = $val;
            $imGroupUser = $this->where(['im_gid' => $input['im_gid'], 'user_id' =>$member])->whereIn('status', [0,3])->first();
            if (!$imGroupUser)
            {
                return ['code' => 1, 'msg' => '用户不存在'];
            }

            if ($imGroupUser['role'] == 2)
            {
                return ['code' => 1, 'msg' => '已经是群管理员'];
            }

            $option = ConfigBusiness::thirdPartyFirst('im');
            $optionValue = $option->value;
            switch($optionValue)
            {
                case ($optionValue == DefaultService::HUANXIN_IM):  // 环信
                    $groupServices= new GroupServices();
                    $groupServiceInfo = $groupServices->addChatGroupsAdmin($input['im_gid'],$member );
                    break;
                case ($optionValue == DefaultService::RONGYUN_IM):  // 融云
                    $groupServiceInfo['code'] = 200;
                    break;
                case ($optionValue == DefaultService::NETEASE_IM):  // 网易
                    $groupServices= new NetGroupServices();
                    $groupServiceInfo = $groupServices->addGroupManager($input['im_gid'],$userId, $memberList);
                    break;
                default:
                    $groupServiceInfo['code'] = 400;
                    break;
            }

            if ($groupServiceInfo['code'] != 200)
            {
                return ['code' => 1, 'msg' => '添加失败'];
            }

            $imGroupUser->role = 2;
            $flag = $imGroupUser->save();
            if (!$flag)
            {
                return ['code' => 1, 'msg' => '添加失败'];
            }
        }

        return ['code' => 0, 'id' => $this->id, 'msg' => '添加成功'];
    }

    /**
     * @desc 移除群管理员
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/24 14:58
     */
    public function downManager($input, $userId = 0)
    {
        $ImGroup = new ImGroup();
        $imGroup = $ImGroup->where('im_gid', $input['im_gid'])->first();
        if (!$imGroup)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        if ($imGroup['user_id'] != $userId)
        {
            return ['code' => 1, 'msg' => '权限不足'];
        }

        $member = $input['member_id'];
        $memberList = explode(",",$member);
        foreach ($memberList as $key =>&$val)
        {
            $member = $val;
            $imGroupUser = $this->where(['im_gid' => $input['im_gid'], 'user_id' => $member])->whereIn('status', [0,3])->first();
            if (!$imGroupUser)
            {
                return ['code' => 1, 'msg' => '用户不存在'];
            }

            if ($imGroupUser['role'] != 2)
            {
                return ['code' => 1, 'msg' => '操作失败'];
            }

            $option = ConfigBusiness::thirdPartyFirst('im');
            $optionValue = $option->value;
            switch($optionValue)
            {
                case ($optionValue == DefaultService::HUANXIN_IM):  // 环信
                    $groupServices= new GroupServices();
                    $groupServiceInfo = $groupServices->delChatGroupsAdmin($input['im_gid'],$member);
                    break;
                case ($optionValue == DefaultService::RONGYUN_IM):  // 融云
                    $groupServiceInfo['code'] = 200;
                    break;
                case ($optionValue == DefaultService::NETEASE_IM):  // 网易
                    $groupServices= new NetGroupServices();
                    $groupServiceInfo = $groupServices->removeGroupManager($input['im_gid'],$userId, [$member]);
                    break;
                default:
                    $groupServiceInfo['code'] = 400;
                    break;
            }

            if ($groupServiceInfo['code'] != 200)
            {
                return ['code' => 1, 'msg' => '移除失败'];
            }

            $imGroupUser->role = 3;
            $flag = $imGroupUser->save();
            if (!$flag)
            {
                return ['code' => 1, 'msg' => '移除失败'];
            }
        }

        return ['code' => 0, 'id' => $this->id, 'msg' => '移除成功'];
    }

    /**
     * @desc 转让群主
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/24 14:58
     */
    public function turnOwner($input, $userId = 0)
    {
        $ImGroup = new ImGroup();
        $imGroup = $ImGroup->where('im_gid', $input['im_gid'])->first();
        if (!$imGroup)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        if ($imGroup['user_id'] != $userId)
        {
            return ['code' => 1, 'msg' => '权限不足'];
        }

        $imGroupUser = $this->where(['im_gid' => $input['im_gid'], 'user_id' => $input['member_id'], 'status'=>0])->first();
        if (!$imGroupUser)
        {
            return ['code' => 1, 'msg' => '用户不存在'];
        }

        $option = ConfigBusiness::thirdPartyFirst('im');
        $optionValue = $option->value;
        switch($optionValue)
        {
            case ($optionValue == DefaultService::HUANXIN_IM):  // 环信
                $groupServices= new GroupServices();
                $groupServiceInfo = $groupServices->transferChatGroupsAdmin($input['im_gid'],$input['member_id']);
                break;
            case ($optionValue == DefaultService::RONGYUN_IM):  // 融云
                $groupServiceInfo['code'] = 200;
                break;
            case ($optionValue == DefaultService::NETEASE_IM):  // 网易
                $groupServices= new NetGroupServices();
                $groupServiceInfo = $groupServices->changeGroupOwner($input['im_gid'], $userId, $input['member_id'], 2);
                break;
            default:
                $groupServiceInfo['code'] = 400;
                break;
        }

        if ($groupServiceInfo['code'] != 200)
        {
            return ['code' => 1, 'msg' => '转让失败'];
        }

        $imGroupUser->role = 1;
        $flag = $imGroupUser->save();
        if (!$flag)
        {
            return ['code' => 1, 'msg' => '转让失败'];
        }

        // 群主更新普通群员
        $imGroupOwner = $this->where(['im_gid' => $input['im_gid'], 'user_id' => $userId, 'status'=>0])->first();
        $imGroupOwner->role = 3;
        if (!$imGroupOwner->save())
        {
            return ['code' => 1, 'msg' => '转让失败'];
        }

        // 更新group群主的用户id
        $imGroup->user_id = $input['member_id'];
        if (!$imGroup->save())
        {
            return ['code' => 1, 'msg' => '转让失败'];
        }

        return ['code' => 0, 'id' => $this->id, 'msg' => '转让成功'];
    }

    /**
     * @desc 设置群聊免打扰 status 1
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/12/2 14:58
     */
    public function setGruopDisturb($input, $userId)
    {
        $imGroupUser = $this->where(['user_id' => $userId, 'im_gid' => $input['im_gid']])->whereIn('status', [0,3])->first();
        if (!$imGroupUser)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        $imGroupUser->no_disturb = $input['status'] ?? 0; // 1是免打扰， 0默认打扰
        $imGroupUser->save();

        return ['code' => 0, 'id' => $this->id, 'msg' => '设置成功'];
    }

    /**
     * @desc 设置是否显示群成员昵称
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/12/2 14:58
     */
    public function setGroupShowName($input, $userId)
    {
        $imGroupUser = $this->where(['user_id' => $userId, 'im_gid' => $input['im_gid']])->whereIn('status', [0,3])->first();
        if (!$imGroupUser)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        $imGroupUser->show_name = $input['status'] ?? 0; // 0 不显示，1显示
        $imGroupUser->save();

        return ['code' => 0, 'id' => $this->id, 'msg' => '设置成功'];
    }

    /**
     * @desc 设置群聊聊天背景
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/12/2 14:58
     */
    public function setGroupCover($input, $userId)
    {
        $imGroupUser = $this->where(['user_id' => $userId, 'im_gid' => $input['im_gid']])->whereIn('status', [0,3])->first();
        if (!$imGroupUser)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        $imGroupUser->chat_cover = $input['cover'] ?? ''; // 聊天背景
        $imGroupUser->save();

        return ['code' => 0, 'id' => $this->id, 'msg' => '修改成功'];
    }

    /**
     * @desc 设置好友备注
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/12/2 14:58
     */
    public function setGroupNote($input, $userId)
    {
        $userFriend = $this->where(['user_id' => $userId, 'im_gid' => $input['im_gid']])->whereIn('status', [0,3])->first();
        if (!$userFriend)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        $userFriend->note_name = $input['note_name'] ?? ''; // 备注
        $userFriend->save();

        return ['code' => 0, 'id' => $this->id, 'msg' => '修改成功'];
    }

    /**
     * @desc 群管和群主退出群聊
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/23 14:58
     */
    public function outGroup($input, $userId = 0)
    {
        $ImGroup = new ImGroup();
        $imGroup = $ImGroup->where('im_gid', $input['im_gid'])->first();
        if (!$imGroup)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        if ($imGroup['user_id'] == $userId)
        {
            return ['code' => 1, 'msg' => '群主不能退出群聊'];
        }

        $imGroupUser = $this->where(['im_gid' => $input['im_gid'], 'user_id' => $userId])->whereIn('status', [0,3])->first();
        if (!$imGroupUser)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        if ($imGroupUser && $imGroupUser['role'] == 1)
        {
            return ['code' => 1, 'msg' => '群主不能退出群聊'];
        }

        $option = ConfigBusiness::thirdPartyFirst('im');
        $optionValue = $option->value;
        switch($optionValue)
        {
            case ($optionValue == DefaultService::HUANXIN_IM):  // 环信
                $groupServices= new GroupServices();
                $groupServiceInfo = $groupServices->delChatGroupsMember($input['im_gid'], $userId);
                if ($groupServiceInfo['code'] != 200)
                {
                    return ['code' => 1, 'msg' => '退出失败'];
                }
                break;
            case ($optionValue == DefaultService::RONGYUN_IM):  // 融云
                $groupServices= new GroupService();
                $groupServiceInfo = $groupServices->quitGroup($userId, $input['im_gid']);
                if ($groupServiceInfo['code'] != 200)
                {
                    return ['code' => 1, 'msg' => '退出失败'];
                }
                break;
        }

        $imGroupUser->delete();
        if ($imGroupUser->trashed())
        {
            $imGroup->decrement('users_count');
            return ['code' => 0, 'msg' => '退出成功'];
        }
        else
        {
            return ['code' => 1, 'msg' => '退出失败'];
        }
    }


    /**
     * @desc 群管和群主修改群名称
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/23 14:58
     */
    public function setGroupName($input, $userId = 0)
    {
        $imGroup = new ImGroup();
        $imGroup = $imGroup->where('im_gid', $input['im_gid'])->first();
        if (!$imGroup)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        $imGroupUser = $this->where(['im_gid' => $input['im_gid'], 'user_id' => $userId])->whereIn('status', [0,3])->first();
        if (!$imGroupUser)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        if ($imGroupUser && !in_array($imGroupUser['role'], [1,2]))
        {
            return ['code' => 1, 'msg' => '权限错误'];
        }

        $groupServices= new GroupServices();
        $isAllow = $imGroup['is_allow'] ? true : false;
        $audit = ($isAllow == 1) ? true : false; // true 不需要审核， false 需要审核,默认false
        $open = ($imGroup['open'] == 1) ? true : false;
        $groupServiceInfo = $groupServices->updateGroup($input['name'],$imGroup['description'], $isAllow, $audit, $open, $input['im_gid']);
        if ($groupServiceInfo['code'] != 200)
        {
            return ['code' => 1, 'msg' => '修改失败'];
        }
        $imGroup->name = $input['name'];
        $imGroup->save();

        return ['code' => 0, 'msg' => '修改成功'];
    }

    /**
     * @desc 群管和群主修改入群许可
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/23 14:58
     */
    public function setGroupAudit($input, $userId = 0)
    {
        $imGroup = new ImGroup();
        $imGroup = $imGroup->where('im_gid', $input['im_gid'])->first();
        if (!$imGroup)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        $imGroupUser = $this->where(['im_gid' => $input['im_gid'], 'user_id' => $userId])->whereIn('status', [0,3])->first();
        if (!$imGroupUser)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        if ($imGroupUser && !in_array($imGroupUser['role'], [1,2]))
        {
            return ['code' => 1, 'msg' => '权限错误'];
        }

        $groupServices= new GroupServices();
        $isAllow = $input['is_allow'] ? true : false; // 1 允许 0 不允许
        $audit = ($isAllow == 1) ? true : false; // true 不需要审核， false 需要审核,默认false
        $open = ($imGroup['open'] == 1) ? true : false;
        $groupServiceInfo = $groupServices->updateGroup($imGroup['name'],$imGroup['description'], $isAllow, $audit, $open, $input['im_gid'], 2);
        if ($groupServiceInfo['code'] != 200)
        {
            return ['code' => 1, 'msg' => '修改失败'];
        }

        $imGroup->is_allow = $input['is_allow'];
        $imGroup->save();

        return ['code' => 0, 'msg' => '修改成功'];
    }

    /**
     * @desc 扫码添加单个群员
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/23 14:58
     */
    public function addScanMember($input, $userId = 0)
    {
        $ImGroup = new ImGroup();
        $imGroup = $ImGroup->where('im_gid', $input['im_gid'])->first();
        if (!$imGroup)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        $imGroupUser = $this->where(['im_gid' => $input['im_gid'], 'user_id' => $userId])->whereIn('status', [0,3])->first();
        if ($imGroupUser)
        {
            return ['code' => 1, 'msg' => '用户已经是群成员'];
        }

        $otherGroupUser = $this->where(['im_gid' => $input['im_gid'], 'user_id' => $input['member_id']])->whereIn('status', [0,3])->first();
        if (!$otherGroupUser)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        $auditStatus = 0;
        if (in_array($otherGroupUser['role'], [1,2]))
        {
            $auditStatus = 1;
        }

        if ($imGroup['is_audit'] == 0)
        {
            $auditStatus = 1;
        }

        $this->im_gid = $input['im_gid'];
        $this->user_id = $userId;;
        $this->other_uid = $input['member_id'];
        $this->audit_status = $auditStatus;;
        $flag = $this->save();

        if (!$flag)
        {
            return ['code' => 1, 'msg' => '添加失败'];
        }

        if ($auditStatus == 1)
        {
            $imGroup->increment('users_count');
        }

        $message = ($auditStatus == 1) ? '扫码成功' : '等待群管理审核';

        return ['code' => 0, 'id' => $this->id, 'msg' => $message];
    }

    /**
     * @desc 群主群管确认审核群员通过 支持多个审核
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/12/7 14:58
     */
    public function auditMember($input, $userId = 0)
    {
        $ImGroup = new ImGroup();
        $imGroup = $ImGroup->where('im_gid', $input['im_gid'])->first();
        if (!$imGroup)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        $imGroupUser = $this->where(['im_gid' => $input['im_gid'], 'user_id' => $userId])->whereIn('status', [0,3])->first();
        if (!$imGroupUser)
        {
            return ['code' => 1, 'msg' => '系统错误'];
        }

        if ($imGroupUser && !in_array($imGroupUser['role'], [1,2]))
        {
            return ['code' => 1, 'msg' => '权限不足'];
        }

        $member = $input['member_id'];
        $memberList = explode(",",$member);
        $service['usernames'] = $memberList;
        $groupServices= new GroupServices();
        $groupServiceInfo = $groupServices->addChatGroupsMembers($input['im_gid'], $service,);
        if ($groupServiceInfo['code'] != 200)
        {
            return ['code' => 1, 'msg' => '添加失败'];
        }

        // 审核通过
        $this->where(['im_gid' => $input['im_gid']])->whereIn('user_id', $memberList)->update(["audit_status" => 1]);

        $imGroup->increment('users_count', count($memberList));

        return ['code' => 0, 'id' => $this->id, 'msg' => '审核成功'];
    }

    /**
     * @desc 群组群员管理
     * @param string $imGid 群组环信id
     * @param int $userId 用户id
     * @param int $limit 每页默认10个
     * @param int $offset 从那条数据开始
     * @return mixed
     * @author zhouzhou
     * @time 2021/11/23 16:50
     */
    public function memberLoginList($imGid, $userId = 0, $limit = 10, $offset = 0)
    {
        $list = $this->withTrashed()->select('id', 'im_gid', 'user_id', 'role', 'status', 'other_uid', 'remove_uid', 'created_at', 'updated_at')->with(['group' => function($q){
            $q->select('im_gid','name','description','face');
        }])->with(['role' => function($q){
            $q->select('id','name');
        }])->with(['user' => function($q){
            $q->select('id','nickname','headimg');
        }])->with(['invite', 'remove'])->where(['im_gid'=>$imGid])
            ->orderBy('id', 'asc')
            ->limit($limit)
            ->offset($offset)
            ->get();

        return $list;
    }

    /**
     * @desc 群组群员管理
     * @param string $imGid 群组环信id
     * @param int $userId 用户id
     * @param int $limit 每页默认10个
     * @param int $offset 从那条数据开始
     * @return mixed
     * @author zhouzhou
     * @time 2021/12/6 16:50
     */
    public function inviteConfirmList($imGid, $userId = 0)
    {
        $list = $this->where(['im_gid'=>$imGid, 'audit_status'=>0])->with(['invite'])->select('other_uid', DB::raw('count(*) as num'))
            ->groupBy('other_uid')
            ->get();

        return $list;
    }

    /**
     * @desc 邀请详情
     * @param array $input 群组的id
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/12/7 14:58
     */
    public function inviteConfirmDetail($input, $userId = 0)
    {
        $list = $this->select('im_gid','user_id','role','apply_note','other_uid')->where(['im_gid'=>$input['im_gid'], 'audit_status'=>0, 'other_uid'=>$input['other_uid']])
            ->with(['user' => function($q){
                $q->select('id','nickname','headimg');
            }])->with(['invite'])
            ->get();

        return $list;
    }

    /**
     * @desc 权限群员管理 分页获取群组成员删除用到，不显示群主
     * @param string $imGid 群组环信id
     * @param int $userId 用户id
     * @param int $limit 每页默认10个
     * @param int $offset 从那条数据开始
     * @return mixed
     * @author zhouzhou
     * @time 2021/11/23 16:50
     */
    public function roleMemberList($imGid, $userId = 0, $limit = 10, $offset = 0)
    {
        // 自己在群的权限
        $imGroupUserRole = $this->where(['im_gid' => $imGid, 'user_id' => $userId])->whereIn('status', [0,3])->first();
        $role = $imGroupUserRole['role'];

        $list = $this->select('id', 'im_gid', 'user_id', 'role', 'status')->with(['group' => function($q){
            $q->select('im_gid','name','description','face');
        }])->with(['role' => function($q){
            $q->select('id','name');
        }])->with(['user' => function($q){
            $q->select('id','nickname','headimg');
        }])->when(($role == 1), function ($query)  {
            return $query->whereIn('role',[2,3]);
        })->when(($role == 2), function ($query)  {
            return $query->where('role',3);
        })->where(['im_gid'=>$imGid, 'audit_status'=>1])->whereIn('status', [0,3])
            ->where('user_id', '!=', $userId)
            ->orderBy('role', 'asc')
            ->limit($limit)
            ->offset($offset)
            ->get();

        return $list;
    }

    /**
     * @desc 所有群的列表
     * @param int $userId 用户id
     * @param int $limit 每页默认10个
     * @param int $offset 从那条数据开始
     * @return mixed
     * @author zhouzhou
     * @time 2021/11/23 16:50
     */
    public function chatList($userId = 0, $limit = 10, $offset = 0)
    {
        $list = $this->select('id', 'im_gid', 'user_id', 'role', 'status')->with(['group' => function($q){
            $q->select('im_gid','id','name','user_id','description','face','max_count','users_count');
        }])->where(['audit_status'=>1,'user_id'=>$userId])->whereIn('status', [0,3])
            ->orderBy('id', 'desc')
            ->limit($limit)
            ->offset($offset)
            ->get();

        $groupList = [];
        foreach ($list as $key =>&$val)
        {
            if (!empty($val['group']) && ($val['group'] != null))
            {
                $groupList[$key] = $val['group'];
            }
        }

        $groupList = array_values($groupList);

        return $groupList;
    }

    /**
     * @desc 拉取环信所有的聊天记录
     * @param int $time 时间
     * @return mixed
     * @author zhouzhou
     * @time 2021/11/23 16:50
     */
    public function chatRecord()
    {
        $option = ConfigBusiness::thirdPartyFirst('im');
        $optionValue = $option->value;
        // $optionValue = "huanxin_im";
        switch($optionValue)
        {
            case ($optionValue == DefaultService::HUANXIN_IM):  // 环信
                $chatServices = new ChatServices();
                $todayTime = date( "YmdH"); // 2021122115
                $start = $todayTime - 1;
                $res = $chatServices->getChatRecord($start);
                if ($res['code'] == 200)
                {
                    // 环信的数据处理
                    $insertChat = $this->huanFileData($res);
                    $imHuanChatMessage = new ImHuanChatMessage();
                    $imHuanChatMessage->insert($insertChat);
                }
                break;
            case ($optionValue == DefaultService::RONGYUN_IM):  // 融云
                $chatServices = new RongChatService();
                $todayTime = date( "YmdH"); // 2021122115
                $start = $todayTime - 1;
                $res = $chatServices->getChatRecord($start);
                if ($res['code'] == 200)
                {
                    // 融云的数据处理
                    $insertChat = $this->rongHandle($res);
                    $imRongChatMessage = new ImRongChatMessage();
                    $imRongChatMessage->insert($insertChat);
                }
                break;
            case ($optionValue == DefaultService::NETEASE_IM):  // 网易云信
                $chatServices = new NeteaseChatServices();
                $todayTime = date( "YmdH"); // 2021122115
                $start = (time() - 3600)."000";
                $begin = time()."000";

                $imGroup = new ImGroup();
                $relateList = $imGroup->relateGroupList(3);

                // 同步群组聊天记录
                foreach ($relateList as $key =>&$val)
                {
                    try{
                        $res = $chatServices->queryGroupMsg($val['im_gid'],$val['user_id'],$start,$begin);
                        if ($res['code'] == 200)
                        {
                            $insertChat = $this->neteaseGroupHandle($res, $val['user_id'] ,$val['im_gid']);
                            $imNeteaseChatMessage = new ImNeteaseChatMessage();
                            if ($insertChat)
                            {
                                $imNeteaseChatMessage->insert($insertChat);
                            }
                        }
                    }catch (\Exception $e)
                    {
                        \Log::info(['oper_group_id'=>$val['im_gid']]);
                    }
                }

                // 查询所有好友列表
                $imUserFriend = new ImUserFriend();
                $allFriendList = $imUserFriend->allFriendList();

                // 同步单个好友聊天记录
                foreach ($allFriendList as $key =>&$val)
                {
                    try{
                        $res = $chatServices->querySessionMsg($val['user_id'],$val['other_uid'], $start, $begin);
                        if ($res['code'] == 200)
                        {
                            $insertChat = $this->neteaseHandle($res, $val['user_id'], $val['other_uid'],$val['id']);
                            $imNeteaseChatMessage = new ImNeteaseChatMessage();
                            if ($insertChat)
                            {
                                $imNeteaseChatMessage->insert($insertChat);
                            }
                        }
                    }catch (\Exception $e)
                    {
                        \Log::info(['oper_id'=>$val['id']]);
                    }
                }


                break;
        }



    }


    /**
     * @desc 环信封装方法，数据处理
     * @param $res
     * @return array
     * @author zhouzhou
     * @time 2021/12/22 9:36
     */
    public function huanFileData($res)
    {
        $url = $res['data']['data'][0]['url'];
        $data = read_gz($url);
        $data = str_replace("}\n",'},',$data);
        $data = rtrim($data,',');
        $data =  '['.$data.']';
        $data =  json_decode($data, true);
        $insertChat = [];
        foreach ($data as $key =>&$val)
        {
            if ($val['payload']['bodies'][0]['type']!= 'cmd')
            {
                $insertChat[$key]['chat_type'] = $val['chat_type'];

                $insertChat[$key]['longitude'] = "";
                $insertChat[$key]['latitude'] = "";
                switch($val['payload']['bodies'][0]['type'])
                {
                    case "txt":  // 文本
                        $insertChat[$key]['content'] = $val['payload']['bodies'][0]['msg'];
                        break;
                    case "img":  // 图片
                        $insertChat[$key]['content'] = $val['payload']['bodies'][0]['url'];
                        break;
                    case "audio":  // 音频
                        $insertChat[$key]['content'] = $val['payload']['bodies'][0]['url'];
                        break;
                    case "video":  // 视频
                        $insertChat[$key]['content'] = $val['payload']['bodies'][0]['url'];
                        break;
                    case "loc":  // 地址
                        $insertChat[$key]['content'] = $val['payload']['bodies'][0]['addr'];
                        $insertChat[$key]['longitude'] = $val['payload']['bodies'][0]['lng'];
                        $insertChat[$key]['latitude'] = $val['payload']['bodies'][0]['lat'];
                        break;
                    default:
                        break;
                }
                $insertChat[$key]['msg_type'] = $val['payload']['bodies'][0]['type'];
                $insertChat[$key]['from_user'] = $val['from'];
                $insertChat[$key]['to_user'] = $val['to'];
                $insertChat[$key]['direction'] = $val['direction'];
                $insertChat[$key]['msg_id'] = $val['msg_id'];
                $insertChat[$key]['created_at'] = intval($val['timestamp']/1000);
            }
        }

        $insertChat = array_values($insertChat);

        return $insertChat;
    }

    /**
     * @desc 融云的数据处理
     * @param $groupId
     * @return array
     * @author zhouzhou
     * @time 2021/12/22 17:18
     */
    public function rongHandle($res)
    {
        $url = $res['data']['url'];
        $fileCon = file_get_contents($url);
        $tmp = storage_path().'/app/zip';
        @mkdir($tmp,0777);
        $localPath = $tmp.'456.zip';
        file_put_contents($localPath, $fileCon);
        $zip = zip_open($localPath);
        $contents = array();
        if ($zip){
            while($zip_entry = zip_read($zip)){
                $name = zip_entry_name($zip_entry);
                if ($name != '.' && $name != '..' && $name != ''){
                    $file = zip_entry_read($zip_entry,zip_entry_filesize($zip_entry));
                    //$file 为读取到的内容 需做处理并存储数据库 参考get_overview方法
                    $key = explode('.',$name);
                    $contents[$key[0]] = auto_read($file);
                }
            }
        }

        zip_close($zip);
        $contents = array_values($contents)[0];

        $contentArr = array_filter(explode(PHP_EOL, $contents));
        $contentArr = array_map(function ($item) {
            $patten = "/^\d{4}\/\d{1,2}\/\d{1,2}\s+\d{2}:\d{2}:\d{2}/";
            return preg_replace($patten, '', trim($item));
        }, $contentArr);

        $insertChat = [];

        foreach ($contentArr as $key =>&$val)
        {
            $val = json_decode($val,true);
            $insertChat[$key]['msg_id'] = $val['msgUID'];
            $insertChat[$key]['from_user'] = $val['fromUserId'];
            $insertChat[$key]['to_user'] = $val['targetId'];
            $insertChat[$key]['created_at'] = intval($val['timestamp']/1000);
            $insertChat[$key]['chat_type'] = empty($val['GroupId']) ? 'chat' : 'groupchat';
            $insertChat[$key]['is_flag_word'] = empty($val['isSensitiveWord']) ? 0 : 1;

            switch($val['classname'])
            {
                case "RC:ImgMsg":  // 图片
                    $insertChat[$key]['content'] = $val['content']['content'];
                    $insertChat[$key]['msg_type'] = 'img';
                    break;
                case (in_array($val['classname'],['RC:VcMsg','RC:HQVCMsg'])):  //语音
                    $insertChat[$key]['content'] = $val['content']['remoteUrl'];
                    $insertChat[$key]['msg_type'] = 'audio';
                    break;
                case "RC:TxtMsg":  // 文本
                    $insertChat[$key]['content'] = $val['content']['content'];
                    $insertChat[$key]['msg_type'] = 'txt';
                    break;
                case "RC:FileMsg":  // 文件
                    $insertChat[$key]['content'] = $val['content']['fileUrl'];
                    $insertChat[$key]['msg_type'] = 'file';
                    break;
                case "RC:SightMsg":  // 视频
                    $insertChat[$key]['content'] = $val['content']['sightUrl'];
                    $insertChat[$key]['msg_type'] = 'video';
                    break;
                default:
                    break;
            }
        }

        $insertChat = array_values($insertChat);
        unlink($localPath);

        return $insertChat;
    }

    /**
     * @desc 网易云数据处理
     * @param $res
     * @param int $fromUid 发送人
     * @param int $otherUid 接收人
     * @return array
     * @author zhouzhou
     * @time 2021/12/27 15:23
     */
    public function neteaseHandle($res, $fromUid, $otherUid,$operId = 0)
    {
        $insertChat = [];
        $msgs = $res['data']['msgs'];
        try{
            if (is_array($msgs))
            {
                foreach ($msgs as $key =>&$val)
                {
                    if ($fromUid != $val['from'])
                    {
                        break;
                    }
                    $insertChat[$key]['msg_id'] = $val['msgidclient'];
                    $insertChat[$key]['from_user'] = $val['from'];
                    $insertChat[$key]['to_user'] = $otherUid;
                    $insertChat[$key]['created_at'] = intval($val['sendtime']/1000);
                    $insertChat[$key]['chat_type'] = 'chat';
                    switch($val['type'])
                    {
                        case 0:  // 文本
                            $insertChat[$key]['content'] = $val['body']['msg'];
                            $insertChat[$key]['msg_type'] = 'txt';
                            break;
                        case 1:  // 图片
                            $insertChat[$key]['content'] = $val['body']['url'];
                            $insertChat[$key]['msg_type'] = 'img';
                            break;
                        case 2:  // 语音
                            $insertChat[$key]['content'] = $val['body']['url'];
                            $insertChat[$key]['msg_type'] = 'audio';
                            break;
                        case 3:  // 视频消息
                            $insertChat[$key]['content'] = $val['body']['url'];
                            $insertChat[$key]['msg_type'] = 'video';
                            break;
                        case 4:  // 地理位置
                            $insertChat[$key]['content'] = $val['body']['title'];
                            $insertChat[$key]['longitude'] = $val['body']['lng'];
                            $insertChat[$key]['latitude'] = $val['body']['lat'];
                            $insertChat[$key]['msg_type'] = 'loc';
                            break;
                        case 5:  // 文件消息
                            $insertChat[$key]['content'] = $val['body']['url'];
                            $insertChat[$key]['msg_type'] = 'file';
                            break;
                        default:
                            $insertChat[$key]['content'] = '通知';
                            $insertChat[$key]['msg_type'] = 'other';
                            break;
                    }
                }

                $insertChat = array_values($insertChat);

                return $insertChat;
            }
        }catch (\Exception $e)
        {
            \Log::info(['oper_id'=>$operId]);
        }

        return false;
    }

    /**
     * @desc 网易云数据处理
     * @param $res
     * @param int $fromUid 发送人
     * @param int $otherUid 接收人
     * @return array
     * @author zhouzhou
     * @time 2021/12/27 15:23
     */
    public function neteaseGroupHandle($res, $fromUid,$toGroupId = 0)
    {
        $insertChat = [];
        $msgs = $res['data']['msgs'];
        unset($msgs[0]);
        try{
            if (is_array($msgs))
            {
                foreach ($msgs as $key =>&$val)
                {
                    $insertChat[$key]['msg_id'] = $val['msgidclient'];
                    $insertChat[$key]['from_user'] = $val['from'];
                    $insertChat[$key]['to_user'] = $toGroupId;
                    $insertChat[$key]['created_at'] = intval($val['sendtime']/1000);
                    $insertChat[$key]['chat_type'] = 'groupchat';
                    switch($val['type'])
                    {
                        case 0:  // 文本
                            $insertChat[$key]['content'] = $val['body']['msg'];
                            $insertChat[$key]['msg_type'] = 'txt';
                            break;
                        case 1:  // 图片
                            $insertChat[$key]['content'] = $val['body']['url'];
                            $insertChat[$key]['msg_type'] = 'img';
                            break;
                        case 2:  // 语音
                            $insertChat[$key]['content'] = $val['body']['url'];
                            $insertChat[$key]['msg_type'] = 'audio';
                            break;
                        case 3:  // 视频消息
                            $insertChat[$key]['content'] = $val['body']['url'];
                            $insertChat[$key]['msg_type'] = 'video';
                            break;
                        case 4:  // 地理位置
                            $insertChat[$key]['content'] = $val['body']['title'];
                            $insertChat[$key]['longitude'] = $val['body']['lng'];
                            $insertChat[$key]['latitude'] = $val['body']['lat'];
                            $insertChat[$key]['msg_type'] = 'loc';
                            break;
                        case 5:  // 文件消息
                            $insertChat[$key]['content'] = $val['body']['url'];
                            $insertChat[$key]['msg_type'] = 'file';
                            break;
                        default:
                            $insertChat[$key]['content'] = '通知';
                            $insertChat[$key]['msg_type'] = 'other';
                            break;
                    }
                }

                $insertChat = array_values($insertChat);

                return $insertChat;
            }
        }catch (\Exception $e)
        {
            \Log::info(['oper'=>$toGroupId]);
        }

        return false;
    }

    /**
     * @desc 共同的群聊列表
     * @param int $userId 用户id
     * @param int $limit 每页默认10个
     * @param int $offset 从那条数据开始
     * @return mixed
     * @author zhouzhou
     * @time 2021/11/23 16:50
     */
    public function commonGroup($input, $userId = 0, $limit, $offset)
    {
        $otherUid = $input['other_uid'] ?? 0;
        $userGroupIds = $this->select('im_gid')->where(['user_id'=>$userId])->whereIn('status',[0,3])->pluck('im_gid')->toArray();

        $otherUserGroupIds = $this->select('im_gid')->where(['user_id'=>$otherUid])->whereIn('status',[0,3])->pluck('im_gid')->toArray();
        $interGroupIds = array_intersect($userGroupIds,$otherUserGroupIds);

        $ImGroupModel = new ImGroup();
        $query = $ImGroupModel->where(['status'=>0])->whereIn('im_gid',$interGroupIds);
        $list = $query->select('id','im_gid','user_id','face','name','description','max_count','users_count')->orderBy('id', 'desc')
            ->limit($limit)
            ->offset($offset)
            ->get();

        return $list;
    }

    /**
     * @desc 查询两个好友共同的群聊个数
     * @param $otherUid 好友的用户id
     * @param $uid 自己的用户id
     * @return mixed
     * @author zhouzhou
     * @time 2021/12/22 10:44
     */
    public function groupComotCount($otherUid, $userId)
    {
        $userGroupIds = $this->select('im_gid')->where(['user_id'=>$userId])->whereIn('status',[0,3])->pluck('im_gid')->toArray();
        $otherUserGroupIds = $this->select('im_gid')->where(['user_id'=>$otherUid])->whereIn('status',[0,3])->pluck('im_gid')->toArray();
        $interGroupIds = array_intersect($userGroupIds,$otherUserGroupIds);

        $ImGroup = new ImGroup();
        $count = $ImGroup->where('status',0)->whereIn('im_gid',$interGroupIds)->count();

        return $count;
    }

    /**
     * @desc 查询是否加入了这个群
     * @param stringt $imGid 群组id
     * @param int $userId 用户id
     * @return int
     * @author zhouzhou
     * @time 2021/12/23 17:58
     */
    public function isJoinGroup($imGid, $userId)
    {
        $groupUser = $this->where(['user_id' => $userId, 'im_gid' => $imGid])->whereIn('status',[0,3])->first();

        return !empty($groupUser) ? 1 : 0;
    }

    /**
     * @desc 获取群组前四的用户生成头像
     * @param string $gid 群组id
     * @param int $limit 默认前4
     * @return mixed
     * @author zhouzhou
     * @time 2022/1/4 14:27
     */
    public function getGroupUserIds($gid, $limit = 4)
    {
        return $this->select('user_id')->where(['im_gid'=>$gid])->whereIn('status',[0,3])->orderBy('id', 'asc')->limit($limit)->pluck('user_id')->toArray();
    }

    /**
     * @desc 更新群组头像
     * @param string $gid 群组id
     * @return mixed
     * @author zhouzhou
     * @time 2022/1/4 14:48
     */
    public function updateGroupHeading($gid)
    {
        // 获取群组前四的用户
        $userIds = $this->getGroupUserIds($gid, 4);

        // user表查询用户头像
        $userModel =new User();
        $usersList = $userModel->getUserByIds($userIds);
        $usersHeading = array_column($usersList, 'headimg');

        $groupImg = [];

        $tmp = public_path().'/img';
        @mkdir($tmp,0777);
        foreach ($usersHeading as $key =>$val)
        {
            $resourceImg = radius_img($val);

            // 生成图片
            imagepng($resourceImg, "{$tmp}/{$gid}_{$key}.png");
            $groupImg[] = "{$tmp}/{$gid}_{$key}.png";
        }

        $groupImgCopy = [];
        foreach ($groupImg as $k =>$v)
        {
            $resourceImgCopy = radius_img_copy($v);

            // 生成图片
            imagepng($resourceImgCopy, "img/{$gid}_{$k}.png");
            $groupImgCopy[] = "./img/{$gid}_{$k}.png";
            imagedestroy($resourceImgCopy);
        }

        $groupAover = getGroupAvatar($groupImgCopy,1,"./img/{$gid}.jpg");

        //删除图片
        foreach ($groupImg as $key =>&$val)
        {
            $urlImg = "{$tmp}/{$gid}_{$key}.png";
            unlink($urlImg);
        }

        if ($groupAover)
        {
            $file = public_path()."/img/{$gid}.jpg";
            $aliyunUpload = new AliyunUploadServices();
            $res = $aliyunUpload->uploadAliImg($file, 2, $gid);
            $fileUrl = $res['info']['url'];//返回的文件地址
            return $fileUrl;
        }

        return '';
    }












}
